package io.renren.modules.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.R;
import io.renren.modules.basic.dao.*;
import io.renren.modules.basic.entity.*;
import io.renren.modules.work.Utils.ManageConstant;
import io.renren.modules.work.Utils.ManagePublicMethod;
import io.renren.modules.work.dao.InStockDao;
import io.renren.modules.work.entity.InStockEntity;
import io.renren.modules.work.service.InStockService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: liguanghao
 * @Date: 2019/10/16 10:19
 * @Version 1.0
 */
@Service("inStockService")
public class InStockServiceImpl extends ServiceImpl<InStockDao,InStockEntity> implements InStockService {
    @Autowired
    private MtCcWarehousPositionRelatDao mtCcWarehousPositionRelatDao;
    @Autowired
    private MtCcTaskRunInfoDao mtCcTaskRunInfoDao;
    @Autowired
    private MtCcWarehousRankDao mtCcWarehousRankDao;
    @Autowired
    private MtCcTaskRunInfoDetLogDao mtCcTaskRunInfoDetLogDao;
    @Autowired
    private MtCcTaskRunInfoDetDao mtCcTaskRunInfoDetDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R checkInForMainTask(Map<String, Object> params) {
        //获取任务id、入库方式.
        String id = String.valueOf(params.get("taskRunInfoId"));
        Integer taskRunInfoId = Integer.parseInt(id);
        String way = String.valueOf(params.get("way"));
        //判断当前有没有任务在执行
        //int count = mtCcTaskRunInfoDao.selectRunning();
        Integer count = mtCcTaskRunInfoDao.selectCount(new QueryWrapper<MtCcTaskRunInfoEntity>().eq("status", "1"));
        if (count==0) {
            //查询主任务详情，修改任务状态
            MtCcTaskRunInfoEntity mtCcTaskRunInfoEntity = mtCcTaskRunInfoDao.selectById(taskRunInfoId);
            mtCcTaskRunInfoEntity.setStatus(1);
            mtCcTaskRunInfoDao.updateById(mtCcTaskRunInfoEntity);
            //判断是否为“自动分配”方式
            if (String.valueOf(params.get("way")).equals("自动分配")) {
                //查找最内的空库位或空托盘库位
                MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity = mtCcWarehousPositionRelatDao.selectInsidePosition();
                //为null则代表仓库满了
                if (mtCcWarehousPositionRelatEntity==null){
          return R.error("仓库没有空库位可用，请手动分配！");
                }
                //查询库位别名
                MtCcWarehousRankEntity mtCcWarehousRankEntity = mtCcWarehousRankDao.selectById(mtCcWarehousPositionRelatEntity.getWarehousPositionId());
                //新建子任务
                MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity=null;
                mtCcTaskRunInfoDetEntity.setWarehousRankId(mtCcWarehousRankEntity.getId());
                mtCcTaskRunInfoDetEntity.setWarehousRankName(mtCcWarehousRankEntity.getAnotherName());
                mtCcTaskRunInfoDetEntity.setTaskRunId(taskRunInfoId);
                mtCcTaskRunInfoDetEntity.setTaskType(1);
                mtCcTaskRunInfoDetEntity.setStatus(0);
                mtCcTaskRunInfoDetEntity.setTaskDetCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,String.valueOf(params.get("doorWay"))));
                mtCcTaskRunInfoDetEntity.setModel(mtCcTaskRunInfoEntity.getModel());
                mtCcTaskRunInfoDetEntity.setUnit(mtCcTaskRunInfoEntity.getUnit());
                mtCcTaskRunInfoDetEntity.setCreateTime(new Date());
                //插入任务明细表，记录日志
                mtCcTaskRunInfoDetDao.insert(mtCcTaskRunInfoDetEntity);

                MtCcTaskRunInfoDetLogEntity mtCcTaskRunInfoDetLogEntity=null;
                mtCcTaskRunInfoDetLogEntity.setCreateTime(mtCcTaskRunInfoDetEntity.getCreateTime());
                mtCcTaskRunInfoDetLogEntity.setWarehousRankId(mtCcTaskRunInfoDetEntity.getWarehousRankId());
                mtCcTaskRunInfoDetLogEntity.setWarehousRankName(mtCcTaskRunInfoDetEntity.getWarehousRankName());
                mtCcTaskRunInfoDetLogEntity.setTaskRunId(taskRunInfoId);
                mtCcTaskRunInfoDetLogEntity.setTaskType(1);
                mtCcTaskRunInfoDetLogEntity.setStatus(0);
                mtCcTaskRunInfoDetLogEntity.setTaskDetCode(mtCcTaskRunInfoDetEntity.getTaskDetCode());
                mtCcTaskRunInfoDetLogEntity.setModel(mtCcTaskRunInfoDetEntity.getModel());
                mtCcTaskRunInfoDetLogEntity.setUnit(mtCcTaskRunInfoDetEntity.getUnit());
                mtCcTaskRunInfoDetLogDao.insert(mtCcTaskRunInfoDetLogEntity);
                return R.ok("生成子任务成功，请继续操作！");
            }
            else{
                //手动分配库位时
                String warehousRankId = String.valueOf(params.get("warehousRankId"));
                //库位信息
                MtCcWarehousRankEntity mtCcWarehousRankEntity = mtCcWarehousRankDao.selectById(Integer.parseInt(warehousRankId));
                //库位对应货物的明细信息
                MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity = mtCcWarehousPositionRelatDao.selectOne(new QueryWrapper<MtCcWarehousPositionRelatEntity>().eq("warehous_position_id", "warehousRankId"));
                //判断库位是否为空 0-可用，1-被占用
                if (mtCcWarehousRankEntity.getIsOccupy()==1){
                    //手动选择的库位被占用新建两条子任务
                    MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity=null;
                    mtCcTaskRunInfoDetEntity.setWarehousRankId(mtCcWarehousRankEntity.getId());
                    mtCcTaskRunInfoDetEntity.setWarehousRankName(mtCcWarehousRankEntity.getAnotherName());
                    mtCcTaskRunInfoDetEntity.setTaskRunId(taskRunInfoId);
                    mtCcTaskRunInfoDetEntity.setTaskType(0);//出库
                    mtCcTaskRunInfoDetEntity.setStatus(0);
                    mtCcTaskRunInfoDetEntity.setTaskDetCode(ManagePublicMethod.creatOrderCode(ManageConstant.OUT_STOCK_ORDER_TYPE,String.valueOf(params.get("doorWay"))));
                    mtCcTaskRunInfoDetEntity.setModel(mtCcWarehousPositionRelatEntity.getProductName());
                    mtCcTaskRunInfoDetEntity.setNum(String.valueOf(mtCcWarehousPositionRelatEntity.getQuantity()));
                    mtCcTaskRunInfoDetEntity.setUnit(null);
                    mtCcTaskRunInfoDetEntity.setCreateTime(new Date());
                    mtCcTaskRunInfoDetDao.insert(mtCcTaskRunInfoDetEntity);//新建出库子任务

                    MtCcTaskRunInfoDetLogEntity mtCcTaskRunInfoDetLogEntity=null;
                    mtCcTaskRunInfoDetLogEntity.setCreateTime(mtCcTaskRunInfoDetEntity.getCreateTime());
                    mtCcTaskRunInfoDetLogEntity.setWarehousRankId(mtCcTaskRunInfoDetEntity.getWarehousRankId());
                    mtCcTaskRunInfoDetLogEntity.setWarehousRankName(mtCcTaskRunInfoDetEntity.getWarehousRankName());
                    mtCcTaskRunInfoDetLogEntity.setTaskRunId(taskRunInfoId);
                    mtCcTaskRunInfoDetLogEntity.setTaskType(0);
                    mtCcTaskRunInfoDetLogEntity.setStatus(0);
                    mtCcTaskRunInfoDetLogEntity.setTaskDetCode(mtCcTaskRunInfoDetEntity.getTaskDetCode());
                    mtCcTaskRunInfoDetLogEntity.setModel(mtCcTaskRunInfoDetEntity.getModel());
                    mtCcTaskRunInfoDetLogEntity.setNum(mtCcTaskRunInfoDetEntity.getNum());
                    mtCcTaskRunInfoDetLogEntity.setUnit(mtCcTaskRunInfoDetEntity.getUnit());
                    mtCcTaskRunInfoDetLogDao.insert(mtCcTaskRunInfoDetLogEntity);//新建出库子任务日志

                    mtCcTaskRunInfoDetEntity.setTaskType(1);//改为入库
                    mtCcTaskRunInfoDetEntity.setTaskDetCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,String.valueOf(params.get("doorWay"))));
                    mtCcTaskRunInfoDetEntity.setModel(mtCcTaskRunInfoEntity.getModel());
                    mtCcTaskRunInfoDetEntity.setNum(null);
                    mtCcTaskRunInfoDetEntity.setUnit(mtCcTaskRunInfoEntity.getUnit());
                    mtCcTaskRunInfoDetEntity.setCreateTime(new Date());
                    mtCcTaskRunInfoDetDao.insert(mtCcTaskRunInfoDetEntity);//新建入库子任务

                    mtCcTaskRunInfoDetLogEntity.setCreateTime(mtCcTaskRunInfoDetEntity.getCreateTime());
                    mtCcTaskRunInfoDetLogEntity.setTaskType(mtCcTaskRunInfoDetEntity.getTaskType());
                    mtCcTaskRunInfoDetLogEntity.setTaskDetCode(mtCcTaskRunInfoDetEntity.getTaskDetCode());
                    mtCcTaskRunInfoDetLogEntity.setModel(mtCcTaskRunInfoDetEntity.getModel());
                    mtCcTaskRunInfoDetLogEntity.setNum(mtCcTaskRunInfoDetEntity.getNum());
                    mtCcTaskRunInfoDetLogEntity.setUnit(mtCcTaskRunInfoDetEntity.getUnit());
                    mtCcTaskRunInfoDetLogDao.insert(mtCcTaskRunInfoDetLogEntity);//新建入库子任务日志

                    return R.ok("生成子任务成功，请继续操作！");
                }
                //手动选择的库位可用，新建子任务
                MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity=null;
                mtCcTaskRunInfoDetEntity.setWarehousRankId(mtCcWarehousRankEntity.getId());
                mtCcTaskRunInfoDetEntity.setWarehousRankName(mtCcWarehousRankEntity.getAnotherName());
                mtCcTaskRunInfoDetEntity.setTaskRunId(taskRunInfoId);
                mtCcTaskRunInfoDetEntity.setTaskType(1);
                mtCcTaskRunInfoDetEntity.setStatus(0);
                mtCcTaskRunInfoDetEntity.setTaskDetCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,String.valueOf(params.get("doorWay"))));
                mtCcTaskRunInfoDetEntity.setModel(mtCcTaskRunInfoEntity.getModel());
                mtCcTaskRunInfoDetEntity.setNum(null);
                mtCcTaskRunInfoDetEntity.setUnit(mtCcTaskRunInfoEntity.getUnit());
                mtCcTaskRunInfoDetEntity.setCreateTime(new Date());
                //插入任务明细表，记录日志
                mtCcTaskRunInfoDetDao.insert(mtCcTaskRunInfoDetEntity);

                MtCcTaskRunInfoDetLogEntity mtCcTaskRunInfoDetLogEntity=null;
                mtCcTaskRunInfoDetLogEntity.setCreateTime(mtCcTaskRunInfoDetEntity.getCreateTime());
                mtCcTaskRunInfoDetLogEntity.setWarehousRankId(mtCcTaskRunInfoDetEntity.getWarehousRankId());
                mtCcTaskRunInfoDetLogEntity.setWarehousRankName(mtCcTaskRunInfoDetEntity.getWarehousRankName());
                mtCcTaskRunInfoDetLogEntity.setTaskRunId(taskRunInfoId);
                mtCcTaskRunInfoDetLogEntity.setTaskType(1);
                mtCcTaskRunInfoDetLogEntity.setStatus(0);
                mtCcTaskRunInfoDetLogEntity.setTaskDetCode(mtCcTaskRunInfoDetEntity.getTaskDetCode());
                mtCcTaskRunInfoDetLogEntity.setModel(mtCcTaskRunInfoDetEntity.getModel());
                mtCcTaskRunInfoDetLogEntity.setNum(null);
                mtCcTaskRunInfoDetLogEntity.setUnit(mtCcTaskRunInfoDetEntity.getUnit());
                mtCcTaskRunInfoDetLogDao.insert(mtCcTaskRunInfoDetLogEntity);
                return R.ok("生成子任务成功，请继续操作！");
            }
        }else{
            //当前有任务正在执行
            return R.error("当前有任务正在执行，请等待！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R runInForChildTask(Map<String, Object> params) {
        //更新子任务中数量、状态、库位id
        String taskRunInfoDetId = String.valueOf(params.get("taskRunInfoDetId"));
        MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity = mtCcTaskRunInfoDetDao.selectById(Integer.parseInt(taskRunInfoDetId));
        mtCcTaskRunInfoDetEntity.setNum(String.valueOf(params.get("quantity")));
        mtCcTaskRunInfoDetEntity.setStatus(1);
        String warehousRankId = String.valueOf(params.get("warehousRankId"));//输入的库位id
        if (mtCcTaskRunInfoDetEntity.getWarehousRankId().equals("0")){//若子任务中的库位id为0，0代表没有指定库位
            if (String.valueOf(params.get("way")).equals("自动分配")){
                MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity = mtCcWarehousPositionRelatDao.selectInsidePosition();//查找最内的空库位
                mtCcTaskRunInfoDetEntity.setWarehousRankId(mtCcWarehousPositionRelatEntity.getWarehousPositionId());
            }else{
                mtCcTaskRunInfoDetEntity.setWarehousRankId(Integer.parseInt(warehousRankId));//若是手动分配，填入输入的库位id
            }
        }
        mtCcTaskRunInfoDetDao.updateById(mtCcTaskRunInfoDetEntity);
        /**
         * 调堆垛机执行子任务
         * 若该子任务为出库任务，执行成功后修改库位对应对应表，记录日志，不用新建子任务，直接renturn
         * 若该子任务为入库任务，执行成功后修改库位对应对应表，记录日志
         */

        //本条子任务执行完毕后，主任务数量减去已执行完毕的子任务里的产品总数量
        Integer taskRunId = mtCcTaskRunInfoDetEntity.getTaskRunId();//主任务id
        List<MtCcTaskRunInfoDetEntity> mtCcTaskRunInfoDetEntities = mtCcTaskRunInfoDetDao.selectList(new QueryWrapper<MtCcTaskRunInfoDetEntity>().eq("task_run_id", "taskRunId"));//已经执行完毕的子任务
        int number=0;
        for (int i=0;i<mtCcTaskRunInfoDetEntities.size();i++){
            number+=Integer.parseInt(mtCcTaskRunInfoDetEntities.get(i).getNum());
        }
        MtCcTaskRunInfoEntity mtCcTaskRunInfoEntity = mtCcTaskRunInfoDao.selectById(taskRunId);
        int remainder=Integer.parseInt(mtCcTaskRunInfoEntity.getNum())-number;
        //剩余数量大于0
        if (remainder>0){
            //新建一条子任务
            MtCcTaskRunInfoDetEntity newMtCcTaskRunInfoDetEntity=null;
            newMtCcTaskRunInfoDetEntity.setCreateTime(new Date());
            newMtCcTaskRunInfoDetEntity.setWarehousRankId(0);//不指定库位id
            newMtCcTaskRunInfoDetEntity.setTaskRunId(mtCcTaskRunInfoEntity.getId());
            newMtCcTaskRunInfoDetEntity.setTaskType(1);
            newMtCcTaskRunInfoDetEntity.setTaskDetCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,String.valueOf(params.get("doorWay"))));
            newMtCcTaskRunInfoDetEntity.setModel(mtCcTaskRunInfoEntity.getModel());//主任务里的型号
            newMtCcTaskRunInfoDetEntity.setUnit(mtCcTaskRunInfoEntity.getUnit());//单位
            mtCcTaskRunInfoDetDao.insert(newMtCcTaskRunInfoDetEntity);//插入任务详情表（子任务）

            //新建一条子任务日志
            MtCcTaskRunInfoDetLogEntity newMtCcTaskRunInfoDetLogEntity=null;
            newMtCcTaskRunInfoDetLogEntity.setCreateTime(newMtCcTaskRunInfoDetEntity.getCreateTime());
            newMtCcTaskRunInfoDetLogEntity.setWarehousRankId(0);
            newMtCcTaskRunInfoDetLogEntity.setTaskRunId(newMtCcTaskRunInfoDetEntity.getTaskRunId());
            newMtCcTaskRunInfoDetLogEntity.setTaskType(1);
            newMtCcTaskRunInfoDetLogEntity.setTaskDetCode(newMtCcTaskRunInfoDetEntity.getTaskDetCode());
            newMtCcTaskRunInfoDetLogEntity.setModel(newMtCcTaskRunInfoDetEntity.getModel());
            newMtCcTaskRunInfoDetLogEntity.setUnit(newMtCcTaskRunInfoDetEntity.getUnit());
            mtCcTaskRunInfoDetLogDao.insert(newMtCcTaskRunInfoDetLogEntity);//记录日志
            return R.ok("本条子任务执行完毕，请继续执行下一条子任务！");
        }
        return R.ok("本次任务执行完毕！");
    }

    @Override
    public R joinWaitQueue(Integer id) {
        MtCcTaskRunInfoEntity mtCcTaskRunInfoEntity = mtCcTaskRunInfoDao.selectById(id);
        //验证子任务中的货物总数量
        List<MtCcTaskRunInfoDetEntity> mtCcTaskRunInfoDetEntities = mtCcTaskRunInfoDetDao.selectList(new QueryWrapper<MtCcTaskRunInfoDetEntity>()
                .eq("task_run_id", id));
        int num=0;
        for (MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity:mtCcTaskRunInfoDetEntities) {
            num = num + Integer.parseInt(mtCcTaskRunInfoDetEntity.getNum());
        }
        if (num!=Integer.parseInt(mtCcTaskRunInfoEntity.getNum())){
            return R.error("子任务货物数量总和与主任务数量不符，请仔细核对修改后重新加入待执行队列！");
        }
        mtCcTaskRunInfoEntity.setStatus(4);
        mtCcTaskRunInfoDao.updateById(mtCcTaskRunInfoEntity);
        return R.ok();
    }

    @Override
    public R exitWaitQueue(Integer id) {
        MtCcTaskRunInfoEntity mtCcTaskRunInfoEntity = mtCcTaskRunInfoDao.selectById(id);
        mtCcTaskRunInfoEntity.setStatus(0);
        mtCcTaskRunInfoDao.updateById(mtCcTaskRunInfoEntity);
        return R.ok();
    }
}
